<template>
  <div class="color-picker">
    <div class="color-card" @click="handleShow">
      <div class="color-center" :style="`background-color: ${modelValue}`"></div>
    </div>
    <div class="color-picker-model" v-show="show" @click="handleShow"></div>
    <div class="color-select" v-show="show">
      <ColorPicker :color="colorAttr" @changeColor="changeColor" />
    </div>
  </div>
</template>

<script setup>
  import { ref, defineProps, defineEmits, watch, nextTick } from 'vue';
  import { ColorPicker } from 'yll_color_pick';
  import 'yll_color_pick/dist/yll_color_pick.css';

  const props = defineProps({
    modelValue: {
      type: String,
      default: '#FF0000FF',
    },
  });
  const emit = defineEmits(['update:modelValue']);
  const colorAttr = ref(props.modelValue);
  const show = ref(false);

  watch(
    () => props.modelValue,
    (newValue) => {
      console.log('newValue: ', newValue);
      colorAttr.value = newValue;
    }
  );

  function rgbaToHex({ r, g, b, a }) {
    // 确保值在 0-255 范围内
    r = Math.min(255, Math.max(0, r));
    g = Math.min(255, Math.max(0, g));
    b = Math.min(255, Math.max(0, b));
    a = Math.min(1, Math.max(0, a));
    // 转换 RGB 为 16 进制并转换为大写
    const redHex = r.toString(16).padStart(2, '0').toUpperCase();
    const greenHex = g.toString(16).padStart(2, '0').toUpperCase();
    const blueHex = b.toString(16).padStart(2, '0').toUpperCase();
    // 处理 alpha 通道，转换为 2 位 16 进制并转换为大写
    const alphaHex = Math.round(a * 255)
      .toString(16)
      .padStart(2, '0')
      .toUpperCase();
    // 返回 16 进制字符串
    return `#${redHex}${greenHex}${blueHex}${alphaHex}`;
  }

  const changeColor = (color) => {
    nextTick(() => {
      emit('update:modelValue', rgbaToHex(color.rgba));
    });
  };

  function handleShow() {
    show.value = !show.value;
  }
</script>

<style scoped lang="less">
  .color-picker {
    position: relative;
    .color-card {
      width: 30px;
      height: 30px;
      padding: 4px;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      .color-center {
        display: block;
        cursor: pointer;
        box-sizing: border-box;
        border-radius: 2px;
        width: 100%;
        height: 100%;
        border: 1px solid #999;
      }
    }
    .color-picker-model {
      position: fixed;
      width: 100vw;
      height: 100vh;
      z-index: 10;
      opacity: 0;
      top: 0;
      left: 0;
    }
    .color-select {
      position: absolute;
      top: 35px;
      left: 0;
      z-index: 20;
      &:deep .hu-color-picker {
        width: 220px !important;
      }
    }
  }
</style>
